<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { login } from '@/api/user'
import type { FormInstance, FormRules } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'
const router = useRouter()
const route = useRoute()
const store = useUserStore()

const ruleForm = reactive({
  adminname: 'admin',
  password: '123456'
})

// 校验
const rules = reactive<FormRules>({
  adminname: [
    { required: true, message: '用户名不能为空', trigger: 'blur' },
    { min: 4, message: '用户名必须至少4位', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '密码不能为空', trigger: 'blur' },
    { min: 6, message: '用户名必须至少6位', trigger: 'blur' }
  ]
})

const formRef = ref<FormInstance>()

const onLogin = () => {
  // 校验整个表单
  formRef.value.validate(async valid => {
    if (!valid) return

    // 发请求
    const res = await login({ adminname: ruleForm.adminname, password: ruleForm.password })

    if (res.data.code === 200) {
      ElMessage({
        message: '登录成功~',
        type: 'success'
      })

      // 把用户信息，存储到仓库中
      store.setUserInfo(res.data.data)

      // 登录成功
      router.push((route.query.redirect as string) ?? '/')
    } else {
      // 登录失败
      ElMessage.error('用户名或密码错误！')
    }
  })
}
</script>

<template>
  <div class="login-container">
    <el-card class="box-card">
      <h3 style="text-align: center" class="card-header">嗨购商城后台管理系统</h3>
      <el-divider border-style="dashed" />
      <el-form
        ref="formRef"
        :model="ruleForm"
        :rules="rules"
        label-width="80px"
        class="demo-ruleForm"
        size="large"
        label-position="left"
      >
        <el-form-item label="用户名" prop="adminname">
          <el-input v-model="ruleForm.adminname" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="ruleForm.password" type="password" show-password />
        </el-form-item>
        <el-form-item label-width="0">
          <el-button type="primary" @click="onLogin" style="width: 100%"> 登录 </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<style lang="less" scoped>
.login-container {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  .box-card {
    width: 440px;
    height: 320px;
  }
}
</style>
